package com.kantboot.util.core.application;

import org.springframework.boot.web.server.WebServer;
import org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

@Component
public class PortGetter implements ApplicationContextAware {

    private ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) {
        this.applicationContext = applicationContext;
    }

    public int getPort() {
        if (applicationContext instanceof ServletWebServerApplicationContext) {
            WebServer webServer = ((ServletWebServerApplicationContext) applicationContext).getWebServer();
            return webServer.getPort();
        }
        return -1; // return -1 if the application context is not a web application context
    }
}